package com.pet.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pet.model.common.dtos.ResponseResult;
import com.pet.model.common.enums.AppHttpCodeEnum;
import com.pet.model.user.dtos.LoginDto;
import com.pet.model.user.pojos.ApUser;
import com.pet.user.feign.ApBehaviorEntryFeign;
import com.pet.user.mapper.ApUserMapper;
import com.pet.user.service.ApUserLoginService;
import com.pet.utils.common.AppJwtUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    private ApBehaviorEntryFeign apBehaviorEntryFeign;

    @Override
    public ResponseResult login(LoginDto dto) {
        //1.校验参数
        if(dto.getEquipmentId() == null && (StringUtils.isEmpty(dto.getPassword())&&StringUtils.isEmpty(dto.getPassword()))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.手机号+密码登录
        if(!StringUtils.isEmpty(dto.getPassword())&&!StringUtils.isEmpty(dto.getPassword())){
            //用户登录
            ApUser dbUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (dbUser!=null) {
                String pswd = DigestUtils.md5DigestAsHex((dto.getPassword()+dbUser.getSalt()).getBytes());
                if (dbUser.getPassword().equals(pswd)) {
                    Map<String, Object> map = new HashMap<>();
                    dbUser.setPassword("");
                    dbUser.setSalt("");
                    map.put("token", AppJwtUtil.getToken(dbUser.getId().longValue()));
                    map.put("user", dbUser);
                    return ResponseResult.okResult(map);
                } else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
        }else {
            //3.设备登录
            if(dto.getEquipmentId() == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);

        }

    }

    @Override
    @Transactional
    public ResponseResult register(ApUser dto) {
        // 1. 参数校验
        if (StringUtils.isEmpty(dto.getPhone()) || StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "手机号或密码不能为空");
        }

        // 2. 校验用户名是否已存在
        ApUser existingUser =apUserMapper.selectOne(new QueryWrapper<ApUser>().eq("phone", dto.getPhone()));
        if (existingUser != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "用户名已存在");
        }

        // 3. 创建新用户对象
        ApUser newUser = new ApUser();
        newUser.setName(dto.getName());
        newUser.setPhone(dto.getPhone());
        newUser.setStatus(true);
        newUser.setCreatedTime(new Date());

        // 4. 使用DigestUtils对密码进行加密
        String salt = RandomStringUtils.randomAlphanumeric(5);
        String password = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        newUser.setPassword(password);
        newUser.setSalt(salt);

        // 5. 保存用户到数据库
        try {
            int insert = apUserMapper.insert(newUser);
            if(insert>0){
                ApUser user1 = apUserMapper.selectOne(new QueryWrapper<ApUser>().eq("phone", dto.getPhone()));
                apBehaviorEntryFeign.save(user1.getId(), null);
            }
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "注册失败");
        }

        // 6. 返回注册成功信息
        Map<String, Object> map = new HashMap<>();
        map.put("user", newUser);
        return ResponseResult.okResult(map);
    }
}